import java.util.ArrayList;
import java.util.List;

public class Solution109 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public TreeNode sortedListToBST(ListNode head) {
        List<Integer> list=new ArrayList<>();
        while (head!=null){
            list.add(head.val);
            head=head.next;
        }
        if (list.size()==0){
            return null;
        }
        return dfs(list,0,list.size()-1);
    }

    private TreeNode dfs(List<Integer> list, int start, int end) {
        if (start>end){
            return null;
        }
        int mid=(start+end)/2;
        TreeNode treeNode=new TreeNode(list.get(mid));
        treeNode.left=dfs(list,start,mid-1);
        treeNode.right=dfs(list,mid+1,end);
        return treeNode;
    }

    public static void main(String[] args) {
        System.out.println(new Solution109().sortedListToBST(new ListNode(-10,new ListNode(-3,new ListNode(0,new ListNode(5,new ListNode(9)))))).left.right.val);
    }
}
